package com.haier.waterdevice.general.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

/**
 * 常用工具类
 */
@SuppressLint("SimpleDateFormat")
public class AppUtil {

    private ProgressDialog pBar = null;
    private String sdpath = Environment.getExternalStorageDirectory()
            + "/download";
    private int progress;
    private Context mContext;
    private boolean cancelUpdate = false;

    public static String getAccessToken() {
        return "";
    }

    private final static String TAG = AppUtil.class.getSimpleName();
    public static int number = 100000;

    public static void sleep(long milisecond) {
        try {
            Thread.sleep(milisecond);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getSequenceId() {
        number += 1;
        if (number + "".length() != 6) {
            number = 100000;
        }
        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
        return sd.format(date) + number;
    }

    public static String getIMEICode(Context activity) {
        TelephonyManager tm = (TelephonyManager) activity
                .getSystemService(activity.TELEPHONY_SERVICE);
        return ((TelephonyManager) activity
                .getSystemService(activity.TELEPHONY_SERVICE)).getDeviceId();
    }

    public static String getMACCode(Context activity) {
        // 在wifi未开启状态下，仍然可以获取MAC地址，但是IP地址必须在已连接状态下否则为0
        String macAddress = null;
        String ip = null;
        WifiManager wifiMgr = (WifiManager) activity
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
        if (null != info) {
            macAddress = info.getMacAddress();
            ip = int2ip(info.getIpAddress());
        }
        return macAddress.replaceAll(":", "");
    }

    public static String int2ip(long ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取wifi状态
     *
     * @param context
     * @return 连上wifi为true，没有连上wifi为false
     */
    public static boolean getWifiState(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != manager) {
                NetworkInfo info = manager.getActiveNetworkInfo();
                if (null != info) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 获取网络状态
     *
     * @param context
     * @return -1 no network available 1 wifi connected 2 mobile network connected
     */
    public static int getNetworkFlag(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                NetworkInfo info = manager.getActiveNetworkInfo();
                if (info != null) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else {
                            return 2;
                        }
                    }
                }
            }
        }
        return -1;
    }

    public static boolean isNetWorkAvailable(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 获取网络状态
     *
     * @param context
     * @return -1 no network available 1 wifi connected 2 mobile network connected
     */
    public static int getNetworkFlagNoToast(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (manager != null) {
                NetworkInfo info = manager.getActiveNetworkInfo();
                if (info != null) {
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                            return 1;
                        } else {
                            return 2;
                        }
                    }
                }
            }
        }
        return -1;
    }

    public static boolean isPhoneNum(String str) {
        boolean result = false;
        if (isPhone(str)) {
            if (isMatchedPhoneNumber(str)) {
                result = true;
            } else {
                if (str.contains("-")) {
                    result = true;

                } else {
                    result = false;
                }
            }
        } else {
            result = false;
        }
        return result;
    }

    private static boolean isPhone(String input) {
        String regex = "1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}";
        Pattern p = Pattern.compile(regex);
        return p.matches(regex, input);
    }

    /**
     * 验证手机号
     *
     * @param number
     * @return
     */
    public static boolean isMatchedPhoneNumber(String number) {
        // Pattern p = Pattern
        // .compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        if (number != null) {
            Pattern p = Pattern.compile("^1\\d{10}$");
            Matcher matcher = p.matcher(number);
            boolean isMatched = matcher.matches();
            Log.i("isnumber", isMatched + "");
            return isMatched;
        } else {
            return false;
        }

    }

    /**
     * 验证密码
     *
     * @param password
     * @return
     */
    public static boolean isMatchedPhonePassword(String password) {
        if (password != null) {

            String check = "[a-z0-9A-Z]{6,}";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(password);
            boolean isMatched = matcher.matches();
            Log.i("isPasswor", isMatched + "");
            return isMatched;
        } else {
            return false;
        }
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean isMatchedEmail(String email) {
        // 电子邮件
        if (email != null) {

            String check = "^([a-z0-9A-Z]+[_\\-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            boolean isMatched = matcher.matches();
            Log.i("isemail", isMatched + "");
            return isMatched;
        } else {
            return false;
        }
    }

    /**
     * 验证用户名和密码的格式是否正确
     *
     * @param username
     * @param password
     * @return
     */
    public static boolean checkUserNamePassWord(String username,
            String password) {
        if (isMatchedPhonePassword(password)) {
            if (isMatchedEmail(username) || isMatchedPhoneNumber(username)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取系统当前时间
     *
     * @return
     */
    public static String getNowDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sdf.format(curDate);
        return str;
    }

    /**
     * 获取系统当前详细时间
     *
     * @return
     */
    public static String getNowDateDetial() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(System.currentTimeMillis());
        return nowTime;
    }

    /**
     * 获取当前年月
     *
     * @return
     */
    public static String getCurrentYearMonth() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMM");// 设置日期格式
        String nowTime = df.format(System.currentTimeMillis());
        Log.e("<--nidayede-->", "nowTime=>>>" + nowTime);
        return nowTime;// new Date()为获取当前系统时间
    }

    /**
     * 获取当前年月
     *
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
        String nowTime = df.format(System.currentTimeMillis());
        Log.e("<--nidayede-->", "nowTime=>>>" + nowTime);
        return nowTime;// new Date()为获取当前系统时间
    }

    /**
     * 判断一个字符串是否为null,或长度为0,或为字符null
     *
     * @param str
     * @return
     */
    public static boolean isNull(String str) {
        if (TextUtils.isEmpty(str) || "null".equalsIgnoreCase(str)) {
            return true;
        }

        return false;
    }

    /**
     * 从url中解析出文件名
     *
     * @param url
     * @return
     */
    public static String getFileName(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }

        return url.substring(url.lastIndexOf("/") + 1, url.length());
    }

    public static boolean delete(File file) {
        boolean flag = false;
        try {
            File to = new File(
                    file.getAbsolutePath() + System.currentTimeMillis());
            file.renameTo(to);
            flag = to.delete();
            Log.d(TAG, "Delete file " + file.getName() + "is " + flag);
        } catch (Exception e) {
            Log.d(TAG, "Exec delete file has exception=" + e.getMessage());
        }

        return flag;
    }

    public static boolean saveBitmap(String directory, String fileName,
            Bitmap bitmap) {
        if (TextUtils.isEmpty(directory) || TextUtils.isEmpty(fileName)
                || bitmap == null) {
            L.d(TAG, "Save to file is failed, the file path is " + directory
                    + ", and bitmap is " + bitmap);
            return false;
        }

        boolean result = false;
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdir();
        }

        File file = new File(directory + fileName);
        if (file.exists()) {
            delete(file);
        }

        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            result = true;
        } catch (FileNotFoundException e) {
            L.e(TAG, "Save file " + fileName + " to " + directory
                    + " has exception the message is " + e.getMessage());
        } catch (IOException e) {
            L.e(TAG, "Save file " + fileName + " to " + directory
                    + " has IOexception the message is " + e.getMessage());
        }

        return result;
    }

    public static int dipToPX(Context context, float dpValue) {
        float scale = 0;
        if (context != null) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dpValue * scale + 0.5f);
    }

    public static int pxToDIP(Context context, float pxValue) {
        float scale = 0;
        if (context != null) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 (像素)
     */
    public static int dip2px(Context context, float dpValue) {
        float scale = 0;
        if (context != null) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 (像素) 的单位 转成为 dip
     */
    public static int px2dip(Context context, float pxValue) {
        float scale = 0;
        if (context != null) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (pxValue / scale + 0.5f);
    }

    @SuppressWarnings("deprecation")
    public static int getScreenWidth(Context context) {
        int width = 0;
        if (context != null) {
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            width = wm.getDefaultDisplay().getWidth();
        }
        return width;
    }

    static MediaPlayer mMediaPlayer = null;

    public static void playRingTone(Context ctx, Uri muri) {
        if (ctx == null || muri == null) {
            Log.e("MediaPlayer()--->", "muri is null or ctx is null");
            return;
        }
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(ctx, muri);
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.setLooping(false);
            mMediaPlayer.start();
        }
    }

    public static void releaseTone() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    // 获取Mac地址
    public static String getMacAddress() {
        String result = "";
        String mMac = "";
        result = callCmd("busybox ifconfig", "HWaddr");
        if (result == null) {
            return "";
        }
        if (result.length() > 0 && result.contains("HWaddr")) {
            mMac = result.substring(result.indexOf("HWaddr") + 6,
                    result.length() - 1);
            if (mMac.length() > 1) {
                result = mMac.toLowerCase();
            }
        }
        return result.trim();
    }

    public static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            // 执行命令cmd，只取结果中含有filter的这一行
            line = br.readLine();
            while (line != null && !line.contains(filter)) {
                // result += line;
                Log.i("test", "line: " + line);
            }

            result = line;
            Log.i("test", "result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 去除空格、换行等格式字符
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 调用此方法输入所要转换的时间戳输入例如（1402733340）输出（"2014.06.14"）
     *
     * @param timeStamp
     * @return
     */
    public static String getTimes(String timeStamp) {
        if (!AppUtil.isNull(timeStamp)) {
            String time = timeStamp;
            if (timeStamp.length() == 13) {
                time = timeStamp.substring(0, 10);
            }
            SimpleDateFormat sdr = new SimpleDateFormat("yyyy.MM.dd");
            @SuppressWarnings("unused")
            long lcc = Long.valueOf(time);
            // int i = Integer.parseInt(time);
            String times = sdr.format(new Date(lcc * 1000L));
            return times;
        } else {
            return "";
        }

    }

    /**
     * 获取APP版本号
     *
     * @param activity
     * @return
     */
    public static String getAppVersion(Context activity) {
        try {
            String pkName = activity.getPackageName();
            int versionCode = activity.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionCode + "";
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 大于一万显示万字
     *
     * @param i
     * @return
     */
    public static String getNumStr(int i) {
        if (i < 10000) {
            return String.valueOf(i);
        } else {
            double num = i;
            DecimalFormat df = new DecimalFormat("#.#");
            double d = num / 10000;
            return df.format(d) + "万";
        }
    }

    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (("com.tencent.mobileqq").equals(pn)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断微信是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (("com.tencent.mm").equals(pn)) {
                    return true;
                }
            }
        }

        return false;
    }

    // /**
    // * 获取文件路径
    // *
    // * @param i
    // * @return
    // */
    // public static String getfile_path(int i) {
    // String path = Environment.getExternalStorageDirectory().toString()
    // + File.separator + "waterway" + File.separator;
    // String file[] = new String[] { path + "img", path + "file",
    // path + "head", path + "splash", path + "aptitude",
    // path + "renzheng" };
    // File picFile = new File(file[i]);
    // if (!picFile.exists()) {
    // picFile.mkdirs();
    // }
    // return file[i];
    // }

    public static final String DOWNLOAD_APK_PATH = Environment
            .getExternalStorageDirectory().getPath()
            + "/com.haier/download/apk/";

    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input)) {
            return true;
        }

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    private void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(sdpath, "shuizhidao.apk")),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    public static String scoreType(int type) {
        switch (type) {
            case 0:
                return "新人注册";
            case 1:
                return "上传头像";
            case 2:
                return "绑定手机";
            case 3:
                return "绑定邮箱";
            case 4:
                return "完善资料";
            case 5:
                return "签到1天";
            case 6:
                return "签到2天";
            case 7:
                return "签到3天";
            case 8:
                return "签到4天";
            case 9:
                return "签到5天";
            case 10:
                return "签到6天";
            case 11:
                return "签到7天";
            case 12:
                return "创建圈子";
            case 13:
                return "加入圈子";
            case 14:
                return "发表帖子";
            case 15:
                return "点赞帖子";
            case 16:
                return "帖子抢沙发";
            case 17:
                return "评论帖子";
            case 18:
                return "收藏知识库";
            case 19:
                return "点赞知识库";
            case 20:
                return "评论知识库";
            case 21:
                return "分享邀请";
            case 22:
                return "点击推广";
            case 23:
                return "分享推广";
            case 24:
                return "被审核恶俗";
            case 25:
                return "被审核伤人";
            case 26:
                return "被审核违禁";
            case 27:
                return "发布无用话题";
            case 28:
                return "发布无用评论";
            case 29:
                return "取消点赞";
            case 30:
                return "取消收藏";
            case 31:
                return "收藏帖子";
            case 32:
                return "收藏解决方案";
            case 33:
                return "点赞解决方案";
            case 34:
                return "评论解决方案";
            case 35:
                return "收藏推荐产品";
            case 36:
                return "点赞推荐产品";
            case 37:
                return "评论推荐产品";
            case 38:
                return "收藏活动";
            case 39:
                return "点赞活动";
            case 40:
                return "评论活动";
            default:
                break;
        }
        return "";
    }

    // 获取PackageName
    public static String getVersionName(Context mContext) {
        String mVersionName = null;
        PackageManager pm = mContext.getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            // mVersionName = Double.parseDouble(pi.versionName);
            mVersionName = pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return mVersionName;
    }
}
